<?php
/**
  * wechat php test 微信提供示例demo
  */

require "mysql.php";

$wechatObj = new wechatCallbackapiTest();  //实例化wechatCallbackapiTest类
// $wechatObj->valid(); //使用valid方法
if (!empty($_GET['echostr'])) {
     $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}
function string2array($data)
{
    if ($data == '') return array();
    if (is_array($data)) return $data;
    if (strpos($data, 'array') !== false && strpos($data, 'array') === 0) {
        // 存在安全性威胁
        if (IS_ADMIN) {
            @eval("\$array = $data;");
            return $array;
        } else {
            exit($data . '<hr>兼容性验证失败，请复制当前页面的URL和以上错误代码上报给管理员');
        }
    }
    return unserialize($data);
}


class wechatCallbackapiTest
{
  // public $baidu_id = '20170527000049394';
  // public $baidu_key = 'Y8ncHME6foxlYfMMOEvL';
  public $postObj = '';
  public $token = '';
  public $appID = '';
  public $appsecret = '';

  public function __construct(){
    $database = require($_SERVER ['DOCUMENT_ROOT'].'/config/database.ini.php');
    $this->mysql = new lib_mysqli($database['host'],$database['username'],$database['password'],$database['dbname'],$database['port']);
    $weixin = file_get_contents($_SERVER ['DOCUMENT_ROOT'].'/config/weixin.php');
    $weixin = string2array($weixin);
    $this->appID = $weixin['appid'];
    $this->appsecret = $weixin['appsecret'];
    define("TOKEN", $weixin['token']);

  }
  
    //valid方法是第一次与微信服务器对接的时候调用的，对接好了之后基本上就用不到这方法了
  public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
          echo $echoStr;
          exit;
        }
    }

    //responseMsg方法用来接收用户传过来的数据进行处理，处理完之后返回给微信服务器，微信服务器再返回给用户
    public function responseMsg()
    {
    //get post data, May be due to the different environments
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        //获取微信公众平台推送过来的post数据  json(小型数据)  xml(大型数据)   

        //extract post data
    if (!empty($postStr)){
        //simplexml_load_string 读取字符串里面的xml文档转化为对象
        //simplexml_load_file 获取文件里面的xml转为对象
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $this->postObj = $postObj;
            
                //$keyword 用户发送过来的请求（内容）
        $MsgType = trim($postObj->MsgType);

        switch($MsgType){
          case 'text';
          $contentStr = $this->do_text();//调用文本方法
          break;
          case 'image';
          $contentStr = $this->do_image();//调用图片方法
          break;
          case 'voice';
          $contentStr = $this->do_voice();//调用语音方法
          break;
          case 'event';
          $contentStr = $this->do_event();//调用取消关注事件方法
          break;
          default:
          $contentStr = $this->baiduApi($keyword);//调用翻译平台
          if(!$contentStr){
            $contentStr = $this->alicloudApi($keyword);//调用智能问答api
          }
        }

        //sprintf() 把百分号（%）符号替换成一个作为参数进行传递的变量：
        //sprintf('模板', '第一个%s位置', 第二个%s位置, 第三个%s位置, 第四个%s位置, 第五个%s位置)

        }else {
          echo "";
          exit;
        }
    }
  
  //封装xml模板，返回给用户，相当于ajax返回无刷新
  public function send_text($contentStr){
    $postObj = $this->postObj;

    $fromUsername = $postObj->FromUserName; //谁发送过来的 用户名
    $toUsername = $postObj->ToUserName; //发送给谁的 
    $keyword = trim($postObj->Content); //发送的内容
    $time = time(); 
    $textTpl = "<xml>
          <ToUserName><![CDATA[%s]]></ToUserName>
          <FromUserName><![CDATA[%s]]></FromUserName>
          <CreateTime>%s</CreateTime>
          <MsgType><![CDATA[%s]]></MsgType>
          <Content><![CDATA[%s]]></Content>
          <FuncFlag>0</FuncFlag>
          </xml>";
          
    $msgType = "text";
    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
    echo $resultStr;
  }
  
  //文本类型方法
  public function do_text(){
    $postObj = $this->postObj;

    $fromUsername = $postObj->FromUserName; //谁发送过来的 用户名
    $toUsername = $postObj->ToUserName; //发送给谁的 
    $keyword = trim($postObj->Content); //发送的内容
    echo "";die;
    switch($keyword){
      // case '图文';
      // $contentStr = $this->send_news();
      // break;
      default:
      $contentStr = $this->baiduApi($keyword);//调用翻译平台
      if(!$contentStr){
        $contentStr = $this->alicloudApi($keyword);//调用智能问答api
      }
    }

    //sprintf() 把百分号（%）符号替换成一个作为参数进行传递的变量：
    //sprintf('模板', '第一个%s位置', 第二个%s位置, 第三个%s位置, 第四个%s位置, 第五个%s位置)
    
    //调用模板返回给用户
    $this->send_text($contentStr);
  }
  
  //图片类型方法
  public function do_image(){
    echo "";die;

    $this->send_text('这是图片类型！');
  }
  
  //语音类型方法
  public function do_voice(){
    echo "";die;

    $this->send_text('这是语音类型！');
  }
  
  //取消关注事件方法
  public function do_event(){
    $postObj = $this->postObj;
    $fromUsername = $postObj->FromUserName; //谁发送过来的 用户名
    $toUsername = $postObj->ToUserName; //发送给谁的 
    $Event = trim($postObj->Event); //发送的内容
    $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appID.'&secret='.$this->appsecret);
    $res = json_decode($res, true);
    $this->token = $res['access_token'];
    switch ($postObj->Event)
          {
                case "subscribe":
                    if($postObj->EventKey==''){
                        $this->send_text("您好，欢迎关注安心保保");
                    }else{
                           $u = explode('_',$postObj->EventKey);
                          $memberid = $u['1'];
                          $sql = "select * from fn_member where openid ='".$fromUsername."'";
                          $mem = $this->mysql->get_row($sql);
                          $sql1 = "select * from fn_member where id =".$memberid;
                          $mem1 = $this->mysql->get_row($sql1);
                        if (empty($mem)) {
                            $userinfo = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->token."&openid=".$fromUsername."&lang=zh_CN");
                            $userinfo = json_decode($userinfo,true);
                            // file_put_contents('1.txt',$userinfo);
                            $name= $userinfo['nickname'];
                            $touxiang = $userinfo['headimgurl'];
                            $sex = $userinfo['sex'];
                            $er_openid = $memberid;
                            $bianhao= time().rand(0,9).rand(0,9).rand(0,9).rand(0,9);
                            $inputtime=time();
                            $ins = "insert into fn_member(`openid`,`name`,`touxiang`,`sex`,`er_openid`,`bianhao`,`inputtime`) values('$fromUsername','$name','$touxiang',$sex,'$er_openid','$bianhao',$inputtime) ";
                            $insert = $this->mysql->query($ins);

                            $this->send_text("您还未成为本平台的会员,已为您注册会员,您的推荐人是".$mem1['name']);
                        }else if (!empty($mem) && empty($mem['er_openid'])) {
                          $up = "update fn_member set er_openid =".$memberid." where id =".$mem['id'];
                          $update = $this->mysql->query($up);
                          $this->send_text("已扫描二维码,您的推荐人是".$mem1['name']);
                        }else if(!empty($mem) && !empty($mem['er_openid'])){
                            $this->send_text("您已经扫过二维码了");
                        }
                    }
                    break;
                case "SCAN":
                    $memberid = $postObj->EventKey;
                      $sql = "select * from fn_member where openid ='".$fromUsername."'";
                      $mem = $this->mysql->get_row($sql);
                      $sql1 = "select * from fn_member where id =".$memberid;
                      $mem1 = $this->mysql->get_row($sql1);
                    if (empty($mem)) {
                        $userinfo1 = file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->token."&openid=".$fromUsername."&lang=zh_CN");
                        file_put_contents('1.txt',$userinfo1);
                        $userinfo1 = json_decode($userinfo1,true);
                        $name= $userinfo1['nickname'];
                        $touxiang = $userinfo1['headimgurl'];
                        $sex = $userinfo1['sex'];
                        $er_openid = $memberid;
                        $bianhao= time().rand(0,9).rand(0,9).rand(0,9).rand(0,9);
                        $inputtime=time();
                        $ins1 = "insert into fn_member(`openid`,`name`,`touxiang`,`sex`,`er_openid`,`bianhao`,`inputtime`) values ('$fromUsername','$name','$touxiang',$sex,'$er_openid','$bianhao','$inputtime') ";
                        $insert1 = $this->mysql->query($ins1);
                        $this->send_text("您还未成为本平台的会员,已为您注册会员,您的推荐人是".$mem1['name']);
                        }else if (!empty($mem) && empty($mem['er_openid'])) {
                                $up1 = "update  fn_member set er_openid =".$memberid." where id =".$mem['id'];
                                $update1 = $this->mysql->query($up1);
                                $this->send_text("已扫描二维码，您的推荐人是".$mem1['name']);
                        }else if(!empty($mem) && !empty($mem['er_openid'])){
                           $this->send_text("您已经扫过二维码了");
                        }

                    break;
                case "CLICK":
                    $sql3 = "select * from fn_wx_reply where keyword = '$postObj->EventKey'";
                    $sugg  = $this->mysql->get_row($sql3);
                    $this->send_text($sugg['content']);
                break;
                     //要实现统计分析，则需要扫描事件写入数据库，这里可以记录 EventKey及用户OpenID，扫描时间
          }
    
  }
  
  
  //智能问答api接口
  public function alicloudApi($keyword){
    $host = "http://jisuznwd.market.alicloudapi.com";//接口地址
    $path = "/iqa/query";//路径
    $method = "GET";//get方式
    $appcode = "4a12b9fadc31488985c0e986c7dec7f4";//阿里云的开发者身份
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "question=$keyword";//提问的问题
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, 0);//关闭头部信息
    if (1 == strpos("$".$host, "https://"))
    {
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $res = curl_exec($curl);
    $res = json_decode($res,true);
    return $res['result']['content'];
  }
  
  public function baiduApi($keyword){
    /*
      q TEXT  Y 请求翻译query UTF-8编码
      from  TEXT  Y 翻译源语言 语言列表(可设置为auto)
      to  TEXT  Y 译文语言  语言列表(不可设置为auto)
      appid INT Y APP ID  可在管理控制台查看
      salt  INT Y 随机数 
      sign  TEXT  Y 签名  appid+q+salt+密钥 的MD5值
    */
    $url = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
    //http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
    
    $to = array('tq' => '天气' ,'en' => '英语' , 'yue' => '粤语' , 'wyw' => '文言文' , 'jp' => '日语' , 'cht' => '繁体中文' , 'vie' => '越南语');
    foreach($to as $k => $v){
      //$k 第一遍 en
      //$v 第一遍 英语
      //strpos() 查找字符串中第一次出现的位置
      //str_repeat() 函数把字符串重复指定的次数
      //str_replace() 函数以其他字符替换字符串中的一些字符
      //土豪我们做朋友吧文言文
      if(strpos($keyword,$v)){
        $data['to'] = $k;
        //$keyword == 土豪我们做朋友吧文言文
        $data['q'] = str_replace($v,'',$keyword);
        //$data['q'] == 土豪我们做朋友吧
      }
    }
    
    if($data['to'] == ''){
      return '';
    }
    
    if($data['to'] == 'tq'){
      //百度天气api接口
      //http://api.map.baidu.com/telematics/v3/weather?location={城市名}&output={返回格式}&ak={百度AK}
      //C845576f91f52f4e62bf8d9153644cb8
      $url = 'http://api.map.baidu.com/telematics/v3/weather?location='.$data['q'].'&output=json&ak=C845576f91f52f4e62bf8d9153644cb8';
      $res = $this->api_get($url);
      $res = json_decode($res,true);
      $today = $res['results'][0]['weather_data'][0];
      
      return '今天是：'.$res['date']."\n".
          '天气：'.$today['weather']."\n".
          '风力：'.$today['wind']."\n".
          '气温：'.$today['temperature']."\n".
          '0201天气平台，感谢您的使用！';
      //return $res;
      
    }else{
      $data['from'] = 'auto';
      $data['appid'] = $this->baidu_id;
      $data['salt'] = rand(1,9).rand(1,9);
      $data['sign'] = md5($data['appid'].$data['q'].$data['salt'].$this->baidu_key);
      
      $res = $this->api_get($url,$data);
      $res = json_decode($res,true);
      //return $res['trans_result'][0]['dst'];
      return '源词语：'.$data['q']."\n".
          '翻译成：'.$res['trans_result'][0]['dst']."\n".
          '0201翻译平台，感谢您的使用！';
    }
    
  }
  
  public function send_news(){
    $news_model = '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>%s</ArticleCount>
            <Articles>%s</Articles>
            </xml>';
            
    $news_one = '<item>
            <Title><![CDATA[%s]]></Title> 
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>';
    //直接送数据库查询出来，然后再推送给客户
    
    $data[] = array(
      'Title' => '图文1',
      'Description' => '嘿嘿今天天气好晴朗，好开心啊，心情棒棒哒！',
      'PicUrl' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496206331110&di=4e31ac70d86e53c0ceae5024f18e391f&imgtype=0&src=http%3A%2F%2Fimg1.gamersky.com%2Fimage2013%2F11%2F20131123r_341%2Fimage031_s.jpg',
      'Url' => 'www.dodi.cn'
    );
    
    $data[] = array(
      'Title' => '图文2',
      'Description' => '哈哈今天天气好晴朗，好开心啊，心情棒棒哒！',
      'PicUrl' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496206435435&di=253b5333833d1d21199cfdd7be5b5d93&imgtype=0&src=http%3A%2F%2Fimg1.gtimg.com%2Fln%2Fpics%2Fhv1%2F100%2F66%2F1572%2F102236230.jpg',
      'Url' => 'www.baidu.com'
    );
    
    $data[] = array(
      'Title' => '图文3',
      'Description' => '嘻嘻今天天气好晴朗，好开心啊，心情棒棒哒！',
      'PicUrl' => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1496206485374&di=a8112b0f39c4e2073a460d07e5232f26&imgtype=0&src=http%3A%2F%2Fi.cqnews.net%2Fnews%2Fattachement%2Fjpg%2Fsite82%2F20140525%2F84a6c821c26c14ebba0238.jpg',
      'Url' => 'www.qq.com'
    );
    
    $news = '';
    foreach($data as $k => $v){
      $news .= sprintf($news_one, $v['Title'], $v['Description'], $v['PicUrl'], $v['Url']);
      //sprintf() 把百分号（%）符号替换成一个作为参数进行传递的变量：
            //sprintf('模板', '第一个%s位置', 第二个%s位置, 第三个%s位置, 第四个%s位置, 第五个%s位置)
    }
    
    $postObj = $this->postObj;
    $fromUsername = $postObj->FromUserName; //谁发送过来的 用户名
    $toUsername = $postObj->ToUserName; //发送给谁的
    
    $time = time();
    $news_info = sprintf($news_model, $fromUsername, $toUsername, $time, count($data), $news);
    echo $news_info;
  }
  
  //获取token方法
  public function token(){
    // $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appID.'&secret='.$this->appsecret;
    // $res = $this->api_get($url);
    // $res = json_decode($res,true);
    // $this->token = $res['access_token'];
    $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appID.'&secret='.$this->appsecret);
    $res = json_decode($res, true);
    $this->token = $res['access_token'];
    file_put_contents('token',$res['access_token']);

  }
  
  //判断token有没过期
  public function get_token(){
    //判断token值存不存在
    if(!file_exists('token')){
      //不存在
      $this->token();
    }else{
      //如果存在
      $time = filemtime('token');
      if(time() - $time > 7200){
        //过期
        $this->token();
      }else{
        //获取token里面的值
        $this->token = file_get_contents('token');
      }
    }
  }
  
  //创建菜单栏
  public function create_menu(){
    $this->token = file_get_contents('token');
    $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->token;//创建
    // $url1 = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$this->token;//查询
    // $url2 = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->token;//删除
    $menu = '{
         "button":[
         {
             "name":"买份保险",
             "sub_button":[
             {
               "type":"view",
               "name":"整形保险",
               "url":"http://anxin.my8m.com/index.php?c=content&a=list&catid=4"
            },
            {
               "type":"view",
               "name":"保险咨询",
               "url":"http://anxin.my8m.com/index.php?c=content&a=list&catid=10"
            },
            {
               "type":"view",
               "name":"保险流程",
               "url":"http://anxin.my8m.com/index.php?c=content&a=list&catid=12"
            }]
           }, 
          {
             "name":"理赔",
             "sub_button":[
             {
               "type":"view",
               "name":"理赔备案",
               "url":"http://anxin.my8m.com/index.php?c=beian"
            },
            {
               "type":"view",
               "name":"保险理赔",
               "url":"http://anxin.my8m.com/index.php?c=content&a=list&catid=16"
            }]
           }, 
          {
            "name": "服务", 
            "sub_button": [
              {
                "type": "view", 
                "name": "个人中心", 
                "url":"http://anxin.my8m.com/index.php?s=.&c=member"
               }, 
              {
                "type": "click", 
                "name": "投诉建议", 
                "key": "suggest", 
              }]
          }
           ]
       }';
    $res = $this->api_post($url,$menu);
    var_dump(json_decode($res,true));
  }
  
    // 微信公众平台与开发平台对话并check
  private function checkSignature()
  {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];  
            
    $token = TOKEN;
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
    
    if( $tmpStr == $signature ){
      return true;
    }else{
      return false;
    }
  }
  
  /**
   * 远程获取数据，POST模式
   * 注意：
   * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
   * @param string $url 指定URL完整路径地址
   * @param string $para 请求的数据
   * @param $input_charset 编码格式。默认值：空值
   * * return 远程输出的数据
   */
  function api_post($url, $para,$input_charset='' ) {
    if (empty($url) || empty($para)) {
      return false;
    }
    if (trim($input_charset) != '') {
      $url = $url."_input_charset=".$input_charset;
    }
    $postUrl = $url;
    $curlPost = $para;

    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且显示输出
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);// post传输数据
    $data = curl_exec($ch);//运行curl
    curl_close($ch);

    return $data;
  }
  
  //extension=php_curl.dll  必须开启curl服务才能外链
  
  //远程获取数据，GET模式
  function api_get($url,$get,$input_charset='') {
    $i = 0;
    foreach ($get as $k => $v){
      if($i == 0){
        $url .= '?'.$k.'='.$v;
      }else{
        $url .= '&'.$k.'='.$v;
      }
      $i = 1;        
    }

    if (trim($input_charset) != '') {
      $url = $url."_input_charset=".$input_charset;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$url");
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_HEADER, 0); //如果设为0，则不使用header
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  }
}

?>